//
//  YSOrderReviewCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/9/24.
//  Copyright © 2015年 悦食中国. All rights reserved.
//  评价晒单

#import "YSOrderReviewCtrl.h"
#import "YSOrderReviewCell.h"
#import "SelectImgUtils.h"
#import "YSProgressImageView.h"
#import "YSSelectImageModel.h"
#import "UpYun.h"
#import "YSClubDataTool.h"
#import "YSProductCommentModel.h"

@interface YSOrderReviewCtrl ()<UITableViewDataSource,UITableViewDelegate,UITextViewDelegate,YSOrderReviewItemViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic)YSOrder *order;
@property (strong, nonatomic)NSMutableArray *allFrames;

@property (nonatomic, weak) UIView *currentEditView;
@property (nonatomic, assign) CGFloat moveDis;//移动距离
@property (nonatomic, assign) CGFloat keyboardHeight;//键盘高度，如果为0，代表当前不是编辑模式

@property (nonatomic, strong) UpYun *uy;
@property (strong, nonatomic) NSMutableArray *commitArray;
@property (strong, nonatomic) JGProgressHUD *HUD;

@end

@implementation YSOrderReviewCtrl

- (IBAction)tapAction:(id)sender {
    [self.view endEditing:YES];
}

-(instancetype)initWithOrder:(YSOrder *)order{
    if(self = [super init]){
        self.order = order;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"评价商品"];
    [self itemArrayWithFrames];
    
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView setTableFooterView:[UIView new]];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView setBackgroundColor:PUBLIC_BG];
    
    _commitArray = [NSMutableArray array];
}

-(void)itemArrayWithFrames{
    if(_allFrames){
         [_allFrames removeAllObjects];
    }else{
        _allFrames = [NSMutableArray array];
    }
   
    for (YSCartProduct *product in self.order.prodList) {
        YSOrderReviewFrame *frame = [[YSOrderReviewFrame alloc]init];
        frame.product = product;
        [_allFrames addObject:frame];
    }
}

-(void)deletePictureData:(NSNotification *)nortif{
    NSIndexPath *deletePath = [nortif object];
    NSLog(@"deletePath:%ld-------:%ld",(long)deletePath.row,(long)deletePath.section);
    YSCartProduct *product = self.order.prodList[deletePath.row];
    [product.photosImage removeObjectAtIndex:deletePath.section];
    [self reloadForRowData:deletePath.row];
}

-(void)reloadForRowData:(NSInteger)row{
    [self itemArrayWithFrames];
    NSIndexPath *refresh_row = [NSIndexPath indexPathForRow:row inSection:0];
    NSArray *array = @[refresh_row];
    [_tableView reloadRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationAutomatic];
}

-(void)selectImgWithModel:(YSSelectImageModel *)model{
    [[self.order.prodList[model.row] photosImage] addObject:model.image];
    [self reloadForRowData:model.row];
    [self uploadFile:model];
}

-(void)viewWillAppear:(BOOL)animated{
     [super viewWillAppear:animated];
    //添加键盘弹出与隐藏的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deletePictureData:) name:kDeleteOrderReviewsSelectPictureNortif object:nil];
   
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:kDeleteOrderReviewsSelectPictureNortif object:nil];
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    self.currentEditView = textView;
    if (self.keyboardHeight!=0) {
        [self adjustLocationWithKeyboardHeight:self.keyboardHeight];
    }
    return YES;
}

-(void)textViewDidChange:(UITextView *)textView{
    [[_allFrames[textView.tag] product] setComment:textView.text];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if([text containsString:@"\n"]){
        [textView resignFirstResponder];
    }
    return YES;
}

- (void)keyboardWillShow:(NSNotification *)notif
{
    //在键盘显示的时候去调整view
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    
    self.keyboardHeight = keyboardSize.height;
    [self adjustLocationWithKeyboardHeight:keyboardSize.height];
}

-(void)adjustLocationWithKeyboardHeight:(CGFloat)keyboardHeight{
    //在键盘弹出时也要让tableView能够全屏滚动
    [self.tableView setHeight:SCREENH-NavWithStatusBarH-keyboardHeight];
    
    UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
    CGRect editViewRect = [self.currentEditView convertRect:self.currentEditView.bounds toView:window];
    
    //首页判断键盘有没有遮挡view，如果没有遮挡，那个什么也不做
    CGFloat viewMaxY = CGRectGetMaxY(editViewRect);
    if (viewMaxY+10>SCREENH-keyboardHeight) {
        //代表键盘遮挡了view
        //需要调整uiscrollview的contentoffset移动
        self.moveDis = (viewMaxY+10)-(SCREENH-keyboardHeight);
        [UIView animateWithDuration:0.25 animations:^{
            [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentOffset.y+self.moveDis)];
        }];
    }
}

-(void)keyboardWillHide:(NSNotification*)notif{
    //键盘隐藏时候恢复tableView原本的高度
    [self.tableView setHeight:SCREENH-NavWithStatusBarH-49];
    
    self.keyboardHeight = 0;
    self.currentEditView = nil;
    if (self.tableView.contentOffset.y!=0) {
        [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentOffset.y-self.moveDis)];
    }
    self.moveDis = 0;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _allFrames.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YSOrderReviewCell *cell = [YSOrderReviewCell cellWithTableView:tableView];
    cell.itemView.reviewTV.delegate = self;
    cell.itemView.photosView.tag = indexPath.row;
    cell.itemView.reviewTV.tag  = indexPath.row;
    cell.itemView.selectBtn.tag = indexPath.row;
    [cell setReviewFrame:_allFrames[indexPath.row]];
    cell.itemView.delegate = self;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [_allFrames[indexPath.row] cellHeight];
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (IBAction)publishReviews:(id)sender {
    NSLog(@"publishReviews");
    //1.判断评论是否有为空的
    for (int i = 0; i<_order.prodList.count; i++) {
        YSCartProduct *product =  _order.prodList[i];
        if(ISBLANK(product.comment)){
            ShowTips(@"请将评价填写完整");
            return;
        }
    }
    BOOL isAllUploadSucc = NO;
    for (YSCartProduct *product in _order.prodList) {
        isAllUploadSucc = product.isAllImageUploadSucc;
    }
    
    //2.上传数据
    if(isAllUploadSucc){
        [self productToModel];
        [self commitComment];
    }else{
        //图片上传未完成，弹出进度条
       _HUD = [DialogUtils show];
    }
}

-(void)productToModel{
    [_commitArray removeAllObjects];
    for (YSCartProduct *product in _order.prodList) {
        YSProductCommentModel *model = [YSProductCommentModel new];
        [model setProdId:product.prodId];
        [model setComment:product.comment];
        [model setScore:product.score];
        NSMutableString *prodUrls = [NSMutableString string];
        for (NSString *url in product.photosUrl) {
            [prodUrls appendString:url];
            [prodUrls appendString:@","];
        }
        if(prodUrls.length){
            prodUrls  = [NSMutableString stringWithString:[prodUrls substringToIndex:prodUrls.length-1]];
        }
    
        [model setProdImages:prodUrls];
        [self.commitArray addObject: [model JSONObject]];
    }
    
    BOOL isAllUploadSucc = NO;
    for (YSCartProduct *product in _order.prodList) {
        isAllUploadSucc = product.isAllImageUploadSucc;
    }
    if(isAllUploadSucc&&_HUD!= nil&&![_HUD isHidden]){//所有图片上传完成，进度条关闭，自动上传
        [_HUD dismiss];
        [self commitComment];
    }
}

-(void)commitComment{
    NSString *param =  self.commitArray.JSONString;
    
    [YSClubDataTool recommentProductWithOrderCode:_order.orderCode commentContent:param  success:^(BaseResponse *result) {
        if(result.isSucc){
            NSLog(@"评论成功a a a a a a ");
            [[NSNotificationCenter defaultCenter] postNotificationName:kSubviewsUpdateOrderStatus object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        ShowTips(kRequestFailure)
    }];
}

- (void)uploadFile:(YSSelectImageModel *)model{
        YSCartProduct *product =  _order.prodList[model.row];
        self.uy = [[UpYun alloc] init];
        __weak YSOrderReviewCtrl *ctrl = self;
        __weak UpYun *uuy = self.uy;
        
        self.uy.successBlocker = ^(id data)
        {
            NSDictionary *dic = data;
            NSString *url = [dic objectForKey:@"url"];
            NSLog(@"url:----%@",url);
            [product.photosUrl addObject:url];
            if (product.isAllImageUploadSucc) {
                NSLog(@"END:%.0f",[[NSDate date] timeIntervalSince1970]);
                //代表上传完成一个商品的东西,这时就判断一下是不是所有的都已经上传完成
                BOOL isAllUploadSucc = NO;
                for (YSCartProduct *product in ctrl.order.prodList) {
                    isAllUploadSucc = product.isAllImageUploadSucc;
                }
                if(isAllUploadSucc){
                    //代表所有的都已经上传成功，组织json数据提交
                    [ctrl productToModel];
                }
            }
        };
        self.uy.failBlocker = ^(NSError * error)
        {
            [uuy cancelUpLoad];
           // NSString *message = [error.userInfo objectForKey:NSLocalizedDescriptionKey];
            [product.photosImage removeObjectAtIndex:model.tag];
            [ctrl reloadForRowData:model.row];
        };
        NSLog(@"START:%.0f",[[NSDate date] timeIntervalSince1970]);
        NSData *data = UIImageJPEGRepresentation(model.image, 0.5);
        [self.uy uploadFile:data saveKey:[self getUPYSaveKey]];
}

- (NSString *)getUPYSaveKey{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"/yyyy/MM/dd"];
    //用[NSDate date]可以获取系统当前时间
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    
    //生成32位的随机字符串
    NSString *dataPoint = [NSString randomStringWithLength:32];
    return [NSString stringWithFormat:@"/user/product/comment%@/%.0f%@",currentDateStr,[[NSDate date] timeIntervalSince1970],dataPoint];
}

@end
